import { TYPE_DOUBLE } from '@app-nextmesh/types';
import { toScientificValue } from '@app-nextmesh/utils';
import { Input, InputRef } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { IBaseProps } from './types';
interface IProps extends IBaseProps<number> {
  type: 'double' | 'int';
}
const PRECISION = 10;
/**
 *  double/int 组件
 * TODO 数值需要判断是否合法，暂时由组件自身控制状态
 */
export default function NumberInput({
  type,
  value: initValue,
  disabled,
  onChange: onInputChange,
}: IProps) {
  const [value, setValue] = useState('' + initValue);
  // 显示的数值，根据情况显示科学计数法或原值
  const [displayValue, setDisplayValue] = useState('' + initValue);
  const inputRef = useRef<InputRef>(null);

  useEffect(() => {
    setValue('' + initValue);
    setDisplayValue(toScientificValue(initValue, PRECISION));
  }, [initValue]);
  const handleInputChange = (value: string) => {
    setValue(value);
    setDisplayValue(value);
  };
  // 失去焦点后，检查输入的数字是否合法
  const handleBlur = () => {
    let f = type === TYPE_DOUBLE ? parseFloat(value) : parseInt(value);
    if (isNaN(f)) {
      f = initValue;
    }
    setValue('' + f);
    setDisplayValue(toScientificValue(f, PRECISION));
    onInputChange(f);
  };
  const handleFocus = () => {
    // 获取焦点，设置成原值
    setDisplayValue(value);
  };
  return (
    <Input
      ref={inputRef}
      type='number'
      value={displayValue}
      disabled={disabled}
      onChange={(e) => handleInputChange(e.target.value)}
      onBlur={handleBlur}
      onFocus={handleFocus}
    />
  );
}
